/**
 * 集群部署
 */
//标志，如果flag不存在则点击确认弹出输入 用户名密码页面，存在则点击确认为加入集群功能
var flag;

var Deploy = {
	/**
	 * 发现节点
	 */
	recognize : function(param) {
		var confirmText ="确认";
		/*if(!flag){
			confirmText = "加入集群";
		}else{
			confirmText = "验证用户名和密码";
		}*/
		/*if(param){
			confirmText = "加入集群"
		}*/
		//if(confirmText=="验证用户名和密码"){
			
			common.dialog({
				type : "get",
				url : baseURL + "/deploy/node",
				title : localeMsg.server.search,
				width : 500,
				height :530,
				confirm : function() {
					var ips = new Array();
					$("input[name='nodeIp']:checked").each(function(){
						ips.push($(this).val());
					});
					
					if(ips.length==0){
						common.showTip({
							title : localeMsg.common.warn ,
							text : "请选择节点ip地址或者重新搜索或者点击取消退出！"
						});
						return false;
					}
					//加入集群
					if(flag){
						flag="";
						Deploy.joinCluster(ips);
						//return true;
						
					}else{
						/*if(ips.length==0){
							common.showTip({
								title : localeMsg.common.warn ,
								text : "请选择节点ip地址或者重新搜索或者点击取消退出！"
							});
							return false;
						}else{*/
							
							//弹出输入用户名和密码的页面	
							Deploy.showUserNameAndPassWord(ips);
							return false;
						//}
					}
					
					
					
				},
				/*if(flag){
					confirmText : "加入集群"
				}else{
					confirmText : "验证用户名和密码"
				}*/
				confirmText : confirmText
			});
		/*}else{
			
		}*/
	},
	/**
	 * 搜索节点
	 */
	search : function() {
		if($("#searchNodesForm").form('validate')!=true){
			return;
		}
		var startIp = $("#startIp").val();
		var endIp = $("#endIp").val();
		var prefix = startIp.substring(0, startIp.lastIndexOf("."));
		var startIndex = parseInt(startIp.split(".")[3]);
		var endIndex = parseInt(endIp.split(".")[3]);
		var index = startIndex;
		if(endIndex<startIndex){
			common.showTip({
				title : localeMsg.common.warn ,
				text : "结束ip地址必须大于或等于起始ip地址！"
			});
			return;
		}
		flag="";
		$("#nodeTable tbody").html("");
		
		
		
		
        //if(!startIp && !endIp){
			//alert(1)
		//}else{
			/*var total;
			if(startIp=="" && endIp!=""){
				total=1;
			};
			if(startIp!="" && endIp==""){
				total=1;
			}
			total= endIndex-startIndex;
			alert(total);*/
			
			
		//};
		
		
		//起始ip存在
		if(startIp){
			$("#bar").attr('style','width:0%;');
			$("#tip").html(0);
			$("#main").show();
			var value;
			if(endIp){
				value = endIndex-startIndex+1;
			}else{
				value = 1;
			}
			var count=0;
			ping(startIp);
			
			// 检查ip连通
			function ping(ip) {
				$.ajax({
					type : "post",
					url : baseURL + "/deploy/ping",
					data : {ip: ip},
					success : function(json) {
						/*var nodeRow = new Stringbuilder();
						nodeRow.append('<tr>');
						*/
						//alert(1);
						var nodeRow = "<tr>" +
						"  <td><input type='checkbox' name='nodeIp' value='" + ip + "'></td>" +
						"  <td>" + ip + "</td>";
						
						if (json && json.result == "success") {
							nodeRow += "<td>连接成功</td>";
						} else if(json && json.result == "exist"){
							nodeRow += "<td>已存在集群中</td>";
						} else{
							nodeRow += "<td>连接失败</td>";
						}
						nodeRow += "</tr>";
						
						$("#nodeTable").show();
						$("#nodeTable tbody").append(nodeRow);
						/*if (json && json.result == "failure") {
							$("input[name='nodeIp']:last").attr("disabled","disabled");
						};*/
						if (json && json.result == "success") {
							$("input[name='nodeIp']:last").attr("checked","checked");
							//$("<td>ppp<td/>").insertBefore("tr:last");
							//$("<td>ppp<td/>").insertAfter("input[value='"+ips[i]+"']");
							//$("input[name='nodeIp']:last").attr("disabled","disabled");
						}else{
							$("input[name='nodeIp']:last").attr("disabled","disabled");
							
						};
						index ++;
						ip = prefix + "." + index;
						if(value==1){
							$("#bar").attr('style','width:100%;');
							$("#tip").html(100);
						}else{
							count ++;
							var c = (count/value).toFixed(2);
							$("#bar").attr('style','width:'+c*100+'%;');
							$("#tip").html(c*100);
						}
						//$("#bar").attr('style','width:100%;');
						if (index <= endIndex) {
							ping(ip);
						}
					}
				});
		      }
		}else if(!startIp && endIp){//起始ip不存在，结束ip存在
			$("#bar").attr('style','width:0%;');
			$("#tip").html(0);
			$("#main").show();
             ping(endIp);
			
			// 检查ip连通
			function ping(ip) {
				$.ajax({
					type : "post",
					url : baseURL + "/deploy/ping",
					data : {ip: ip},
					success : function(json) {
						var nodeRow = "<tr>" +
						"  <td><input type='checkbox' name='nodeIp' value='" + ip + "'></td>" +
						"  <td>" + ip + "</td>";
						
						if (json && json.result == "success") {
							nodeRow += "<td>连接成功</td>";
						} else if(json && json.result == "exist"){
							nodeRow += "<td>已存在集群中</td>";
						} else{
							nodeRow += "<td>连接失败</td>";
						}
						nodeRow += "</tr>";
						$("#nodeTable").show();
						$("#nodeTable tbody").append(nodeRow);
						/*if (json && json.result == "failure") {
							$("input[name='nodeIp']:last").attr("disabled","disabled");
						};*/
						if (json && json.result == "success") {
							$("input[name='nodeIp']:last").attr("checked","checked");
							//$("input[name='nodeIp']:last").attr("disabled","disabled");
						}else{
							$("input[name='nodeIp']:last").attr("disabled","disabled");
							
						};
						$("#bar").attr('style','width:100%;');
						$("#tip").html(100);
						//$("#main").hide();
					}
				});
		      }
			
		}else{//起始ip不存在，结束ip不存在
			common.showTip({
				title : localeMsg.common.warn ,
				text : localeMsg.deploy.searchInfo
			});
		}
	},
	/**
	 * 分发agent
	 */
	distribute : function() {
		var ips = new Array();
		$("input[name='nodeIp']").each(function(){
			ips.push($(this).val());
		});
		$.ajax({
			type : "post",
			url : baseURL + "/deploy/distribute",
			data : {ips : ips},
			traditional: true,
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.saveSuccess ,
						success : true
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.common.saveFailed});
				}
			}
		});
	},
	/**
	 * 加入集群
	 * @param ips
	 */
	joinCluster : function(ips) {
		//alert(ips);
		$.ajax({
			type : "post",
			url : baseURL + "/deploy/node/save",
			data : {ips : ips},
			traditional: true,
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.saveSuccess ,
						success : true,
						callback : function() {
							var serverlistUrl = baseURL + "/monitor/server/list"
							$.ajax({
								type : "get",
								url : serverlistUrl,
								dataType : "html",
								success : function(html) {
									// Request successfully and fill the data.
									$("#content").empty().html(html);
								}
							});
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : localeMsg.deploy.saveFailure,success: false});
				}
			}
		});
	},
	validate : function(){
		$('#startIp').validatebox({
			validType : 'ip'
		
		});
		$('#endIp').validatebox({
			validType : 'ip'
		});
	},
	validateUserNameAndPassword : function(){
		$('#userId').validatebox({
			required: true,
	        validType: 'name'
		
		});
		$('#passwordId').validatebox({
			required: true
		});
	},
	/**
	 * 弹窗显示输入用户名和密码的页面
	 */
	showUserNameAndPassWord : function(ips) {
		//alert(ips);
		/*var ips = new Array();
		$("input[name='nodeIp']:checked").each(function(){
			ips.push($(this).val());
		});
		if(ips){
			alert(1)
		}*/
		var title = "请输入用户名和密码";
		if(!flag){
			
			common.dialog({
				obj : "#showUserNameAndPassWord",
				type : "get",
				url : baseURL + "/deploy/showUserNameAndPassWord",
				title : title,
				width : 400,
				confirm : function() {
					//$("#nodeTable").html("");
					//Deploy.recognize("加入集群");
					/*if($("#editTargetForm").form('validate')!=true){
						return;
					}*/
					flag = "success";
					Deploy.saveIpsUserNamePassword(ips);
				},
				//confirmText : "加入集群"
			});
		}
		//alert(1)
		
		/*common.dialog({
			obj : dialog,
			title : localeMsg.group.list,
			width : 680,
			confirm : function(dialog) {
				var groupIdArr = [];
				$(dialog).find("input[name='groupId']:checked").each(function() {
					groupIdArr.push($(this).val());
				});
				if(!(groupIdArr.length>0)) {
					return;
				}
				main.saveTargetGroups(targetId,type,1);
			},
			confirmText : confirmText
			onOpen : function() {
				$("#listGroupForm").ajaxpager({
					target: "#groupList",
					callback: function() {
						Target.showGroupsByPager(targetId, type);
					}
				});
			}
		})
		
		*/
		
		
		
		
		/*var ips = new Array();
		$("input[name='nodeIp']:checked").each(function(){
			ips.push($(this).val());
		});
		if(ips.length==0){
			return;
		}else{
			
			$.ajax({
				type : "post",
				url : baseURL + "/deploy/node/save",
				data : {ips : ips},
				traditional: true,
				success : function(json) {
					if (json.result && json.result == "success") {
						common.showTip({
							title : localeMsg.common.prompt,
							text : localeMsg.common.saveSuccess ,
							success : true,
							callback : function() {
								var serverlistUrl = baseURL + "/monitor/server/list"
								$.ajax({
									type : "get",
									url : serverlistUrl,
									dataType : "html",
									success : function(html) {
										// Request successfully and fill the data.
										$("#content").empty().html(html);
									}
								});
							}
						});
					} else {
						common.showTip({title : localeMsg.common.warn, text : localeMsg.deploy.saveFailure,success: false});
					}
				}
			});
		}*/
	},
	//保存选择的ips，用户名，密码
	saveIpsUserNamePassword : function(ips){
		var ipsString = ips.join();
		
		$("#saveIpsUserNamePasswordForm").ajaxSubmit({
			data : {
				"ips" : ipsString
			},
			success : function(json) {
				if (json) {
					//flag="";
					common.showTip({
						title : localeMsg.common.prompt,
						text : "检测成功",
						success : true,
						callback : function() {
							Deploy.showStatus(json,ips);
						}
					});
				} else {
					common.showTip({title : localeMsg.common.warn, text : "检测失败"});
				}
			}
		});
	},
	showStatus : function(json,ips){
		//json:根据用户名和密码验证成功的所有ips,ips:选中需向后端验证的ips
		$("#main").hide();
		$("#nodeTable tbody").html("");
		/*var x ;
		for(x in json){
			alert(json[x]);
		}*/
		var isExist = false;
		for(var i=0;i<ips.length;i++){
			//alert(json[i])
			var nodeRow = "<tr>" +
			"  <td><input type='checkbox' name='nodeIp' value='" + ips[i] + "'></td>" +
			"  <td>" + ips[i] + "</td>";
			for(var j=0;j<json.length;j++){
				if(json[j]==ips[i]){
					isExist=true;
					break;
				}
			};
			if (isExist==true) {
			nodeRow += "<td>成功</td>";
		    } else {
			nodeRow += "<td>失败</td>";
		    };
			nodeRow += "</tr>";
			
			$("#nodeTable").show();
			$("#nodeTable tbody").append(nodeRow);
			if(isExist==false){
				$("input[value='"+ips[i]+"']").attr("disabled","disabled");
			};
		}
	}
}